import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Grid,
  Chip,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  Avatar,
  Badge
} from '@mui/material';
import {
  Assignment as AssignmentIcon,
  CheckCircle as CheckCircleIcon,
  Cancel as CancelIcon,
  HourglassEmpty as HourglassIcon,
  Build as BuildIcon,
  Visibility as VisibilityIcon
} from '@mui/icons-material';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import apiRequest from '../utils/api';

const ServiceProviderMaintenance = () => {
  const [maintenanceRecords, setMaintenanceRecords] = useState([]);
  const [pendingRecords, setPendingRecords] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedRecord, setSelectedRecord] = useState(null);
  const [openDialog, setOpenDialog] = useState(false);
  const [statusDialog, setStatusDialog] = useState(false);
  const [statusForm, setStatusForm] = useState({
    status: '',
    notes: ''
  });
  const [pendingCount, setPendingCount] = useState(0);

  useEffect(() => {
    loadMaintenanceRecords();
    loadPendingCount();
  }, []);

  const loadMaintenanceRecords = async () => {
    try {
      setLoading(true);
      const [allRecords, pending] = await Promise.all([
        apiRequest.get('/api/maintenance/service-provider'),
        apiRequest.get('/api/maintenance/service-provider/pending')
      ]);
      setMaintenanceRecords(allRecords.data);
      setPendingRecords(pending.data);
    } catch (err) {
      console.error('加载维修记录失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const loadPendingCount = async () => {
    try {
      const response = await apiRequest.get('/api/maintenance/service-provider/pending-count');
      setPendingCount(response.data);
    } catch (err) {
      console.error('加载待处理数量失败:', err);
    }
  };

  const getStatusColor = (status) => {
    const colors = {
      PENDING: 'warning',
      ASSIGNED: 'info',
      IN_PROGRESS: 'primary',
      COMPLETED: 'success',
      CANCELLED: 'error'
    };
    return colors[status] || 'default';
  };

  const getStatusLabel = (status) => {
    const labels = {
      PENDING: '待处理',
      ASSIGNED: '已分配',
      IN_PROGRESS: '处理中',
      COMPLETED: '已完成',
      CANCELLED: '已取消'
    };
    return labels[status] || status;
  };

  const getPriorityColor = (priority) => {
    const colors = {
      LOW: 'success',
      MEDIUM: 'warning',
      HIGH: 'error',
      URGENT: 'error'
    };
    return colors[priority] || 'default';
  };

  const getPriorityLabel = (priority) => {
    const labels = {
      LOW: '低',
      MEDIUM: '中',
      HIGH: '高',
      URGENT: '紧急'
    };
    return labels[priority] || priority;
  };

  const handleStatusUpdate = async () => {
    try {
      await apiRequest.put(`/api/maintenance/${selectedRecord.id}/status`, null, {
        params: statusForm
      });
      loadMaintenanceRecords();
      loadPendingCount();
      setStatusDialog(false);
      setSelectedRecord(null);
    } catch (err) {
      console.error('更新状态失败:', err);
    }
  };

  const handleViewDetails = (record) => {
    setSelectedRecord(record);
    setOpenDialog(true);
  };

  const handleStatusClick = (record) => {
    setSelectedRecord(record);
    setStatusForm({
      status: record.status === 'PENDING' ? 'IN_PROGRESS' : 'COMPLETED',
      notes: ''
    });
    setStatusDialog(true);
  };

  return (
    <Box sx={{ p: 3 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4">
          维修异常管理
        </Typography>
        <Badge badgeContent={pendingCount} color="error">
          <Typography variant="h6" color="text.secondary">
            待处理异常
          </Typography>
        </Badge>
      </Box>

      <Grid container spacing={3}>
        {/* 待处理异常卡片 */}
        <Grid item xs={12} md={4}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                <HourglassIcon color="warning" sx={{ mr: 1 }} />
                <Typography variant="h6">待处理异常</Typography>
              </Box>
              <Typography variant="h3" color="warning.main">
                {pendingRecords.length}
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={4}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                <BuildIcon color="primary" sx={{ mr: 1 }} />
                <Typography variant="h6">处理中</Typography>
              </Box>
              <Typography variant="h3" color="primary.main">
                {maintenanceRecords.filter(r => r.status === 'IN_PROGRESS').length}
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={4}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                <CheckCircleIcon color="success" sx={{ mr: 1 }} />
                <Typography variant="h6">已完成</Typography>
              </Box>
              <Typography variant="h3" color="success.main">
                {maintenanceRecords.filter(r => r.status === 'COMPLETED').length}
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        {/* 维修记录列表 */}
        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                所有维修记录
              </Typography>
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>车辆信息</TableCell>
                      <TableCell>异常类型</TableCell>
                      <TableCell>优先级</TableCell>
                      <TableCell>状态</TableCell>
                      <TableCell>报告时间</TableCell>
                      <TableCell>操作</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {maintenanceRecords.map((record) => (
                      <TableRow key={record.id}>
                        <TableCell sx={{ maxWidth: 200 }}>
                          <Box sx={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
                            <Typography variant="subtitle2" sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                              {record.vehiclePlate}
                            </Typography>
                            <Typography variant="body2" color="text.secondary" sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                              {record.description}
                            </Typography>
                          </Box>
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={record.maintenanceType === 'ABNORMAL_HANDLING' ? '异常处理' : 
                                   record.maintenanceType === 'REGULAR_MAINTENANCE' ? '定期保养' :
                                   record.maintenanceType === 'REPAIR' ? '故障维修' : '紧急维修'}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={getPriorityLabel(record.priority)}
                            color={getPriorityColor(record.priority)}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={getStatusLabel(record.status)}
                            color={getStatusColor(record.status)}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>
                          {format(new Date(record.reportedAt), 'MM/dd HH:mm', { locale: zhCN })}
                        </TableCell>
                        <TableCell>
                          <IconButton
                            onClick={() => handleViewDetails(record)}
                            color="primary"
                          >
                            <VisibilityIcon />
                          </IconButton>
                          {record.status === 'PENDING' && (
                            <IconButton
                              onClick={() => handleStatusClick(record)}
                              color="success"
                            >
                              <AssignmentIcon />
                            </IconButton>
                          )}
                          {record.status === 'ASSIGNED' || record.status === 'IN_PROGRESS' ? (
                            <IconButton
                              onClick={() => handleStatusClick(record)}
                              color="success"
                            >
                              <CheckCircleIcon />
                            </IconButton>
                          ) : null}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* 详情对话框 */}
      <Dialog open={openDialog} onClose={() => setOpenDialog(false)} maxWidth="md" fullWidth>
        <DialogTitle>维修详情</DialogTitle>
        <DialogContent>
          {selectedRecord && (
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom>车辆信息</Typography>
                <Typography>{selectedRecord.vehiclePlate}</Typography>
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom>报告人</Typography>
                <Typography>{selectedRecord.reportedByName}</Typography>
              </Grid>
              <Grid item xs={12}>
                <Typography variant="subtitle2" gutterBottom>异常描述</Typography>
                <Typography>{selectedRecord.description}</Typography>
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom>优先级</Typography>
                <Chip
                  label={getPriorityLabel(selectedRecord.priority)}
                  color={getPriorityColor(selectedRecord.priority)}
                  size="small"
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom>状态</Typography>
                <Chip
                  label={getStatusLabel(selectedRecord.status)}
                  color={getStatusColor(selectedRecord.status)}
                  size="small"
                />
              </Grid>
              {selectedRecord.location && (
                <Grid item xs={12}>
                  <Typography variant="subtitle2" gutterBottom>发生位置</Typography>
                  <Typography>{selectedRecord.location}</Typography>
                </Grid>
              )}
              {selectedRecord.estimatedCost && (
                <Grid item xs={12} md={6}>
                  <Typography variant="subtitle2" gutterBottom>预估费用</Typography>
                  <Typography>¥{selectedRecord.estimatedCost}</Typography>
                </Grid>
              )}
              <Grid item xs={12}>
                <Typography variant="subtitle2" gutterBottom>报告时间</Typography>
                <Typography>
                  {format(new Date(selectedRecord.reportedAt), 'yyyy年MM月dd日 HH:mm', { locale: zhCN })}
                </Typography>
              </Grid>
              {selectedRecord.notes && (
                <Grid item xs={12}>
                  <Typography variant="subtitle2" gutterBottom>备注</Typography>
                  <Typography>{selectedRecord.notes}</Typography>
                </Grid>
              )}
              {selectedRecord.tags && selectedRecord.tags.length > 0 && (
                <Grid item xs={12}>
                  <Typography variant="subtitle2" gutterBottom>标签</Typography>
                  <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
                    {selectedRecord.tags.map((tag, index) => (
                      <Chip key={index} label={tag} size="small" />
                    ))}
                  </Box>
                </Grid>
              )}
            </Grid>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>关闭</Button>
        </DialogActions>
      </Dialog>

      {/* 状态更新对话框 */}
      <Dialog open={statusDialog} onClose={() => setStatusDialog(false)} maxWidth="sm" fullWidth>
        <DialogTitle>更新维修状态</DialogTitle>
        <DialogContent>
          <FormControl fullWidth sx={{ mt: 2 }}>
            <InputLabel>新状态</InputLabel>
            <Select
              value={statusForm.status}
              onChange={(e) => setStatusForm(prev => ({ ...prev, status: e.target.value }))}
              label="新状态"
            >
              <MenuItem value="IN_PROGRESS">处理中</MenuItem>
              <MenuItem value="COMPLETED">已完成</MenuItem>
              <MenuItem value="CANCELLED">已取消</MenuItem>
            </Select>
          </FormControl>
          <TextField
            fullWidth
            multiline
            rows={3}
            label="备注"
            value={statusForm.notes}
            onChange={(e) => setStatusForm(prev => ({ ...prev, notes: e.target.value }))}
            sx={{ mt: 2 }}
            placeholder="请输入处理结果或备注信息..."
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setStatusDialog(false)}>取消</Button>
          <Button onClick={handleStatusUpdate} color="primary" variant="contained">
            确认更新
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default ServiceProviderMaintenance;